// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.chimi.service.impl;

import com.liuxinlong.common.AosException;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.chimi.service.BarCarouselService;
import com.liuxinlong.modules.dao.BarCarouselDao;
import com.liuxinlong.modules.dao.FileManageDao;
import com.liuxinlong.modules.entity.BarCarousel;
import com.liuxinlong.modules.system.service.FileManageService;
import com.liuxinlong.utils.IPUtils;
import com.liuxinlong.utils.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 论坛轮播管理服务层接口实现
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2022-11-09
 */
@Service
@Slf4j
public class BarCarouselServiceImpl implements BarCarouselService {

    @Autowired
    private BarCarouselDao barCarouselDao;

    @Autowired
    private FileManageService fileManageService;

    @Autowired
    private FileManageDao fileManageDao;

    @Override
    public List<Map<String, Object>> pageCarousel(Map<String, Object> queryParam) {
        int startNum = (int) queryParam.get("startNum");
        List<BarCarousel> originalList = barCarouselDao.pageBarCarouselList(queryParam);
        return completeResult(originalList, startNum);
    }

    @Override
    public int getCarouselCount(Map<String, Object> queryParam) {
        return barCarouselDao.getBarCarouselCount(queryParam);
    }

    @Override
    @Transactional
    public void addCarousel(BarCarousel barCarousel) {
        String id = SnowFlake.nextIdStr();
        barCarousel.setId(id);
        barCarouselDao.insert(barCarousel);
        List<String> pictureList = new ArrayList<>();
        if (!StringUtils.isEmpty(barCarousel.getPicture())) {
            pictureList.add(barCarousel.getPicture());
        }
        if (!StringUtils.isEmpty(barCarousel.getPictureMobile())) {
            pictureList.add(barCarousel.getPictureMobile());
        }
        fileManageService.updateBusinessFile(StringUtils.strip(pictureList.toString(),"[]").replaceAll(" +",""), id);
    }

    @Override
    @Transactional
    public void updateCarousel(BarCarousel barCarousel) {
        String id = barCarousel.getId();
        if (StringUtils.isEmpty(id)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改轮播信息异常，轮播不存在！");
        }
        BarCarousel oldInfo = barCarouselDao.selectById(id);
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改轮播信息异常，轮播不存在！");
        }
        barCarouselDao.updateById(barCarousel);
        if (StringUtils.equals(oldInfo.getPicture(),barCarousel.getPicture()) && StringUtils.equals(oldInfo.getPictureMobile(),barCarousel.getPictureMobile())) {
            return;
        }
        List<String> pictureList = new ArrayList<>();
        if (!StringUtils.isEmpty(barCarousel.getPicture())) {
            pictureList.add(barCarousel.getPicture());
        }
        if (!StringUtils.isEmpty(barCarousel.getPictureMobile())) {
            pictureList.add(barCarousel.getPictureMobile());
        }
        fileManageService.updateBusinessFile(StringUtils.strip(pictureList.toString(),"[]").replaceAll(" +",""), id);
    }

    @Override
    @Transactional
    public void deleteCarousel(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "删除轮播信息异常，轮播不存在！");
        }
        BarCarousel oldInfo = barCarouselDao.selectById(id);
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "删除轮播信息异常，轮播不存在！");
        }
        fileManageService.batchInvalidFile(id);
        barCarouselDao.deleteById(id);
    }

    @Override
    @Transactional
    public void updateCarouselStatus(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改轮播状态异常，轮播信息不存在！");
        }
        BarCarousel oldInfo = barCarouselDao.selectById(id);
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改轮播状态异常，轮播信息不存在！");
        }
        // 目标状态 1 启用 0 停用
        int targetStatus = oldInfo.getStatus() == 0 ? 1 : 0;
        if (targetStatus == 1) {
            BarCarousel effectInfo = barCarouselDao.getBarCarouselByIndex(oldInfo.getShowIndex());
            if (!ObjectUtils.isEmpty(effectInfo)) {
                barCarouselDao.updateCarouselStatus(effectInfo.getId(), 0);
            }
        }
        barCarouselDao.updateCarouselStatus(id, targetStatus);
    }

    /**
     * 数据补全转换
     *
     * @param originList 原始数据列表
     * @param startNum   起始查询数
     * @return 补全数据
     */
    private List<Map<String, Object>> completeResult(List<BarCarousel> originList, int startNum) {
        if (ObjectUtils.isEmpty(originList)) {
            return new ArrayList<>();
        }
        Set<String> fileIdList = new HashSet<>();
        Set<String> pictureIdList = originList.stream().map(BarCarousel::getPicture).collect(Collectors.toSet());
        fileIdList.addAll(pictureIdList);
        Set<String> pictureMobileList = originList.stream().map(BarCarousel::getPictureMobile).collect(Collectors.toSet());
        fileIdList.addAll(pictureMobileList);
        Map<String,Map<String,Object>> fileMap = new HashMap<>();
        if (!ObjectUtils.isEmpty(fileIdList)) {
            fileMap = fileManageDao.getFileMapByIds(fileIdList);
        }
        String currentIp = IPUtils.getCurrentIp();
        List<Map<String, Object>> resultList = new ArrayList<>(originList.size());
        int sort = startNum + 1;
        for (BarCarousel record : originList) {
            Map<String, Object> map = ObjectUtils.object2Map(record);
            map.put("sort", sort);
            if (!StringUtils.isEmpty(record.getPicture())) {
                String filePath = fileMap.containsKey(record.getPicture()) ? (String) fileMap.get(record.getPicture()).get("path") : "";
                String path = StringUtils.isEmpty(filePath) ? "" : filePath.replace("upload", "http:\\\\" + currentIp + ":8090\\preview\\upload");
                map.put("pictureUrl",path);
            }
            if (!StringUtils.isEmpty(record.getPictureMobile())) {
                String filePath = fileMap.containsKey(record.getPictureMobile()) ? (String) fileMap.get(record.getPictureMobile()).get("path") : "";
                String path = StringUtils.isEmpty(filePath) ? "" : filePath.replace("upload", "http:\\\\" + currentIp + ":8090\\preview\\upload");
                map.put("pictureMobileUrl",path);
            }
            resultList.add(map);
            sort++;
        }
        return resultList;
    }
}
